import React, { useRef, useEffect } from 'react';
import { useRoute, useNavigation, NavigationProp } from '@react-navigation/native';
import {StyleSheet, Text, View, Image, TouchableOpacity, Alert} from 'react-native';
import { CameraRoll } from "@react-native-camera-roll/camera-roll";
import moment from 'moment';
import ViewShot from 'react-native-view-shot';

interface RouteParams {
  id: number | string;
  chipnameCN: string;
  kitNo: string;
  link: string | number;
  resultShow: string;
  sampleNo: string;
  startTime: string;
}

const DetailsScreen = () => {
  const route = useRoute();
  const params = route.params as RouteParams; // 类型断言
  const { id } = params;  // 获取id
  const navigation = useNavigation<NavigationProp<any>>();
  const viewShotRef = useRef<ViewShot>(null);
  const [fileUri, setFileUri] = React.useState<string>('');
  // 定义一个对象 用来存储详情数据
  const [detail, setDetail] = React.useState<RouteParams>({
    id: 0,
    chipnameCN: '',
    kitNo: '',
    link: '',
    resultShow: '',
    sampleNo: '',
    startTime: '',
  });


  // 根据id获取详情
  const getDetail = async () => {
    try {
      const res = await fetch(`http://127.0.0.1:49152/pcrdataById?id=${id}`);
      const result = await res.json();
      const { chipnameCN, link,  kitNo, resultShow, sampleNo } = result.result;
      const startTime = moment(parseInt(result.result.startTime)).format('YYYY-MM-DD');
      setDetail({
        id,
        chipnameCN,
        kitNo,
        link,
        resultShow,
        sampleNo,
        startTime,
      });
    } catch (error) {
      console.log('error', error);
    }
  }

  useEffect(() => {
    getDetail();
  }, []);


  const handleBack = () => {
    navigation.goBack();
  }

  const handleSave = async () => {
    const currentRef = viewShotRef.current;
    if (currentRef && typeof currentRef.capture === 'function') {
      try {
        const uri = await currentRef.capture();
        if (uri) {
          // Alert.alert('截图成功，已存入相册');
          setFileUri(uri);
          // 保存到相册
          let promise =  CameraRoll.save(uri);
          promise.then(function(result) {
            Alert.alert('保存成功，已存至相册');
          }).catch(function(error) {
            console.log('保存失败: ' + error);
          });
        } else {
          throw new Error('未能成功获取截图');
        }
      } catch (error: any) {
        Alert.alert('截图失败', (error as Error).message);
      }
    } else {
      Alert.alert('无效的引用', '未能获取截图');
    }
  }


  return (
    <View style={styles.container}>
      {/* {
          fileUri  &&  <Image source={{ uri: fileUri }} style={{ width: 200, height: 200 }} />
      } */}
      <View style={styles.innerWrapper}>
        <ViewShot ref={viewShotRef} options={{ format: 'png' }}>
          <View style={styles.inner}>
            <View style={styles.titleBox}>
              <Text style={styles.titleText}>核酸检测报告</Text>
            </View>
            <View style={styles.border1} />
            <View style={styles.infoBox}>
              <View style={styles.infoRow}>
                <Text style={styles.infoRowKey}>检测项目:</Text>
                <Text style={styles.infoRowVal}>{detail.chipnameCN || ''}</Text>
              </View>
              <View style={styles.infoRow}>
                <Text style={styles.infoRowKey}>芯片信息:</Text>
                <Text style={styles.infoRowVal}>{detail.kitNo || ''}</Text>
              </View>
              <View style={styles.infoRow}>
                <Text style={styles.infoRowKey}>样本信息:</Text>
                <Text style={styles.infoRowVal}>{detail.sampleNo || ''}</Text>
              </View>
              <View style={styles.infoRow}>
                <Text style={styles.infoRowKey}>检测时间:</Text>
                <Text style={styles.infoRowVal}>{detail.startTime}</Text>
              </View>
              <View style={styles.border2} />
              <View style={styles.imageRow}>
                <Text style={styles.imageRowKey}>扩增曲线与CT值：</Text>
                <View style={styles.imageRowBox}>
                  <Image source={{uri: `http://127.0.0.1:49152/static/${detail.link}/capture.jpg`}} style={styles.img1}></Image>
                  {/* <Image source={require('../assets/app_images/2.png')} style={styles.img2}></Image> */}
                </View>
              </View>
              <View style={styles.infoRow}>
                <Text  style={styles.infoRowKey}>检测结果:</Text>
                <Text  style={styles.infoRowVal}>{detail.resultShow}</Text>
              </View>
            </View>
          </View>
        </ViewShot>
      </View>
      <View style={styles.btnRow}>
        <TouchableOpacity style={styles.btn} onPress={()=> handleBack()}>
          <Text style={styles.buttonText}>返回</Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.btn} onPress={handleSave}>
          <Text style={styles.buttonText}>保存</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    width: '100%',
    height: '100%',
    paddingLeft: 20,
    paddingRight: 20,
    backgroundColor: '#fff'
  },

  innerWrapper: {
    height: '90%',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
  },

  inner: {
    flex: 1,
    flexDirection: 'column',
    alignItems: 'center',
  },
  titleBox: {
    width: '100%',
    height: 80,
    backgroundColor: '#fff',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center'
  },
  titleText: {
    fontSize: 24,
    color: '#000',
    letterSpacing: 5,
    fontWeight: 'bold',
    backgroundColor: '#fff'
  },

  border1: {
    width: '100%',
    height: 1.5,
    backgroundColor: 'skyblue',
  },

  infoBox: {
    width: '100%',
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: 10,
    paddingBottom: 10
  },
  infoRow: {
    width: '100%',
    paddingTop: 10,
    paddingBottom: 10,
    flexDirection: 'row',
    justifyContent: 'space-between'
  },
  infoRowKey : {
    width: '30%',
    fontSize: 16,
    color: '#000',
    fontWeight: 'bold',
    textAlign: 'left',
    paddingLeft: 10
  },
  infoRowVal : {
    width: '70%',
    fontSize: 14,
    color: '#000',
    textAlign: 'left',
    paddingLeft: 10
  },

  border2: {
    width: '100%',
    height: 1.5,
    backgroundColor: 'skyblue',
    marginTop: 10,
  },
  imageRow: {
    width: '100%',
    marginTop: 10,
    marginBottom: 10,
  },
  imageRowKey: {
    width: '100%',
    fontSize: 16,
    color: '#000',
    fontWeight: 'bold',
    textAlign: 'left',
    paddingLeft: 10,
    paddingTop: 10,
    paddingBottom: 10,
  },
  imageRowBox: {
    width: '100%',
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingTop: 10,
    paddingBottom: 10,
  },
  img1 : {
    width: '98%',
    height: 160,
    resizeMode: 'contain'
  },
  btnRow: {
    width: '100%',
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingTop: 10,
    paddingBottom: 10,
  },
  btn: {
    width: '48%',
    height: 40,
    backgroundColor: 'skyblue',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: 5,
  },
  buttonText : {
    color: '#fff',
    fontSize: 16,
    fontWeight: 'bold',
  },
});

export default DetailsScreen;
